<script setup>
import { useUserStore } from '@/stores/user';
import JWeixin from 'weixin-js-sdk';
import { Toast, Dialog } from 'vant';
import { queryUrlParam } from '@/utils/tools';
import { EiInfo } from '@eplat/ei';
// 调用4j的service
import api4j from '@/api/example';
import { it } from 'vuetify/locale';

const router = useRouter();
const user = useUserStore();
const loading = ref(false);
const finish = ref(false);
const page = reactive({
  pageSize: 10,
  currentPage: 0,
  result: []
});
const onLoad = async () => {
  loading.value = true;
  applyList();
  applyListTreeData();
  loading.value = false;
};

const applyList = async () => {
  // 工作人员维修列表
  const postEiInfo = new EiInfo();
  postEiInfo.set('token', user.getToken);
  await api4j
    .RCRM0103_zcInfo(postEiInfo)
    .then((res) => {
      // console.log('res', res);
      page.result = [];
      const data = res.extAttr.data;
      if (data.length === 0) {
        page.result = [];
        window.location.href =
          'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+api4j.APPID+'&redirect_uri=https%3A%2F%2F' +
          api4j.SERVER_DOMAIN +
          '%2F%23%2FWX%2FWD%2FWXWD02&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
      } else {
        page.result.push(...data);
      }
    })
    .catch((error) => {
      if (error.response && error.response.status === 429) {
        // eslint-disable-next-line no-undef
        Toast('请勿频繁操作');
      }
    });
};

const deleteZCInfo = async (item) => {
  // console.log('item', item);
  // 工作人员维修列表
  const postEiInfo = new EiInfo();
  postEiInfo.set('token', user.getToken);
  postEiInfo.set('zcId', item.zcId);
  Dialog.confirm({
    title: '删除',
    message: '确认删除绑定资产吗？'
  })
    .then(async () => {
      await api4j.RCRM0103_zcInfoDelete(postEiInfo).then((res) => {
        if (res.status == 1) {
          Toast('删除成功');
          onLoad();
          return;
        }
        Toast('未查询到信息');
      });
    })
    .catch(() => {
      // on cancel
    });
};

// 授权
JWeixin.config({
  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
  appId: api4j.APPID, // 必填，公众号的唯一标识
  timestamp: '', // 必填，生成签名的时间戳
  nonceStr: '', // 必填，生成签名的随机串
  signature: '', // 必填，签名
  jsApiList: [] // 必填，需要使用的JS接口列表
});
JWeixin.ready(async () => {
  // 获取用户code
  const code = queryUrlParam('code');
  // 没有授权code
  if (code == null) {
    // Toast('授权失败');
    // 跳转到授权页面
    window.location.href =
      'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+api4j.APPID+'&redirect_uri=https%3A%2F%2F' +
      api4j.SERVER_DOMAIN +
      '%2F%23%2FWX%2FWD%2FWXWD03%3Fabc%3D1&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
  } else {
    // 本地没有token新授权
    // // console.log('进入方法之前:',user.getToken)
    if (user.getToken == '' || user.getToken == undefined) {
      // Toast('正在授权');
      // // console.log('进入方法:',user.getToken)
      const postEiInfo = new EiInfo();
      postEiInfo.set('code', code);
      // 通过code获取用户信息
      await api4j.wxLogin(postEiInfo).then((res) => {
        // 如果授权无效 重新授权
        if (res.status !== 1) {
          //Toast(res.msg);
          window.location.href =
            'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+api4j.APPID+'&redirect_uri=https%3A%2F%2F' +
            api4j.SERVER_DOMAIN +
            '%2F%23%2FWX%2FWD%2FWXWD03%3Fabc%3D1&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
          return;
        }
        //Toast(res.msg);
        // token info存放本地
        user.setUserInfo(
          res.extAttr.token,
          res.extAttr.userInfo.attrs.headimgurl,
          res.extAttr.userInfo.attrs.nickname
        );
        user.setUserNameTel(res.extAttr.username, res.extAttr.phone);
        // // console.log('132',user.getToken)
        // // console.log(user.getHeadimgurl)
        // // console.log(user.getNickname)
        // // console.log('qqqq', res)
        onLoad();
        // 资产不存在,跳转页面进行绑定
        if (res.msg == '授权无资产') {
          router.push('/WX/WD/WXWD01');
        }
      });
    }
  }
});
// 存放最终的资产id
let zcData = [];
let zcDatas = [];
// 存放树
const treeData = ref([]);
// 资产清除
const zcClear = () => {
  cascaderValue1.value = '';
  fieldValue1.value = '';
  // 清空资产
  zcData = [];
  zcDatas = [];
  zcID.value = '';
  val8.value = '';
};
const zcID = ref('');
const shows = ref(false);
const cascaderValue1 = ref('');
const show1 = ref(false);
const fieldValue1 = ref('');
// 定义规则
const fieldNames = {
  text: 'label',
  value: 'id',
  children: 'children'
};
const clearData = () => {
  cascaderValue1.value = '';
};
const applyListTreeData = async () => {
  // eslint-disable-next-line no-unused-vars
  const postEiInfo = new EiInfo();
  await api4j.RCRM0103_zcTree(postEiInfo).then((res) => {
    // console.log('data:', res);
    // console.log('data2:', res.extAttr.treeData);
    treeData.value = res.extAttr.treeData;
    // 处理每个顶级节点 删除空数组Children
    treeData.value.forEach((node) => {
      removeEmptyChildren(node);
    });
  });
};
// 递归删除空数组Children
function removeEmptyChildren(node) {
  if (node.children && node.children.length > 0) {
    // 递归处理子节点
    node.children.forEach((child) => {
      removeEmptyChildren(child);
    });
  } else {
    // 删除children为空数组的属性
    delete node.children;
  }
}
const onFinish1 = ({ selectedOptions }) => {
  // 存放资产id
  zcDatas = [];
  zcID.value = '';
  dataList.value = [];
  if (![selectedOptions.length - 1] == '') {
    //  如果不存在 才push
    if (
      !zcDatas.includes(
        selectedOptions[selectedOptions.length - 1].id +
          '=' +
          selectedOptions.map((option) => option.label).join('/')
      )
    ) {
      zcDatas.push(
        selectedOptions[selectedOptions.length - 1].id +
          '=' +
          selectedOptions.map((option) => option.label).join('/')
      );
      // 查询资产表
      // console.log('===', selectedOptions[selectedOptions.length - 1].id);
      zcID.value = selectedOptions[selectedOptions.length - 1].id;
    }
  }
  show1.value = false;
  fieldValue1.value = selectedOptions.map((option) => option.label).join('/');
};

const qr = async () => {
  if (fieldValue1.value === '' || fieldValue1.value === undefined) {
    Toast('请选择楼层');
    return;
  }
  if (val8.value === '' || val8.value === undefined) {
    Toast('资产不能为空');
    return;
  }

  const postEiInfo = new EiInfo();
  postEiInfo.set(
    'zc',
    zcData.filter((item) => item.assetName === val8.value)
  );
  postEiInfo.set('username', user.getUsername);
  postEiInfo.set('token', user.getToken);
  postEiInfo.set('zcData', zcDatas);
  await api4j.RCRM0103_zcInfoAdd(postEiInfo).then((res) => {
    // console.log('asda', res);
    Toast(res.msg);
  });
  onLoad();
  zcClear();
  shows.value = false;
};
const val8 = ref('');
const show8 = reactive([]);
const dataList = ref([]);
const onConfirm8 = (value, index) => {
  show8[0] = false;
  val8.value = value;
  Toast(`当前资产名称: ${value}`);
};
const onChange8 = (value, index) => {
  Toast(`当前资产名称: ${value}`);
};
const onCancel8 = () => {
  show8.forEach((item, index) => {
    show8[index] = false;
    val8.value = '';
  });
};

const sleectByZcId = async () => {
  if (zcID.value == '') {
    Toast('请先选择楼层');
    show8[0] = false;
    return;
  }
  const postEiInfo = new EiInfo();
  postEiInfo.set('zcID', zcID.value);
  await api4j.RCRM0103_zcIdQuery(postEiInfo).then((res) => {
    if (res.status == 1) {
      // console.log('res', res);
      zcData = res.extAttr.zcData;
      dataList.value = zcData.map((item) => item.assetName);
    }
  });
};
const showPopup = () => {
  shows.value = true;
};
</script>
<template>
  <van-list
    v-model:loading="loading"
    class="working-list"
    :finished="finish"
    finished-text=""
    offset="1"
    @load="onLoad"
  >
    <div
      style="
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        background: #4b75e5;
        height: 65px;
        color: white;
        z-index: 1000;
      "
    >
      <div style="font-size: 20px; padding-top: 20px; text-align: center">我的资产</div>
      <van-button
        to="/WX/WD/WXWD02"
        style="
          background-color: #4b75e5;
          color: white;
          display: flex;
          flex-direction: column;
          align-items: center;
          border: 1px solid #4b75e5;
          margin-top: -32px;
          margin-left: 20px;
        "
      >
        <img
          src="@/assets/tb166.svg"
          style="width: 35px; height: 35px; margin-left: -20px; margin-top: 3px"
          alt=""
        />
      </van-button>
    </div>
    <div style="margin-top: 75px">
      <van-cell-group
        v-for="(item, index) in page.result"
        :key="index"
        style="margin-left: 20px; margin-right: 20px"
        inset
      >
        <van-cell style="width: 100%">
          <div style="display: flex">
            <div>
              <img
                src="@/assets/tb144.svg"
                style="width: 32px; height: 32px; margin-top: 30px"
                alt=""
              />
            </div>
            <div style="margin-left: 20px">
              <div style="font-size: 20px; font-weight: bold; margin-top: 10px">
                {{ item.reserve1.split('/')[1] }}
              </div>
              <div style="margin-top: 5px">
                {{ item.reserve1.split('/').slice(2).join('/') }}/{{ item.reserve2 }}
              </div>
              <div style="margin-top: 5px; width: 240px">{{ item.reserve1.split('/')[0] }}</div>
            </div>
            <van-button
              round
              style="
                width: 30px;
                font-weight: bold;
                color: white;
                display: flex;
                flex-direction: column;
                align-items: center;
                border: 1px solid white;
                margin-top: 30px;
                margin-left: 5px;
              "
              @click="deleteZCInfo(item)"
            >
              <img src="@/assets/tb309.svg" alt="" style="width: 30px; height: 30px" />
            </van-button>
          </div>
        </van-cell>
      </van-cell-group>
      <van-button
        v-if="page.result.length !== 0"
        type="primary"
        style="width: 90%; margin-left: 20px; margin-right: 20px; background-color: #4b75e5"
        @click="shows = true"
        ><span>+&nbsp;新增资产</span></van-button
      >

      <van-popup
        v-model:show="shows"
        class="form-cell-group"
        closeable
        close-icon="close"
        position="bottom"
        close-icon-position="top-right"
        close-icon-size="100px"
        :style="{ width: '100%', height: '80%' }"
        :close="clearData()"
      >
        <div style="margin-top: 50px; margin-left: 16px; display: flex">
          <span style="color: red; margin-top: 9px; margin-right: 2px">*</span>
          <span style="margin-top: 6px">资产信息</span>
          <van-button
            type="default"
            icon="delete-o"
            size="small"
            style="margin-left: 170px"
            plain
            @click="zcClear"
            >清除记录</van-button
          >
        </div>
        <van-field
          required
          label="楼层名称："
          placeholder="请选择楼层"
          center
          readonly
          style="margin-top: 15px"
          @click="show1 = true"
        >
          <template #input>
            <van-cell is-link @click="showPopup">{{
              fieldValue1 == '' ? '请选择楼层' : fieldValue1
            }}</van-cell>
          </template>
        </van-field>
        <van-popup v-model:show="show1" round position="bottom">
          <van-cascader
            v-model="cascaderValue1"
            title="请选择楼层"
            :options="treeData"
            :field-names="fieldNames"
            @close="show1 = false"
            @finish="onFinish1"
          />
        </van-popup>

        <van-field
          v-model="val8"
          class="titles"
          label="资产名称:"
          placeholder="请选择资产名称"
          required
          center
        >
          <template #input>
            <van-cell :value="val8" is-link @click="show8[0] = true">
              {{ val8 == '' || val8 == undefined ? '请选择资产' : val8 }}
            </van-cell>
            <van-popup position="bottom" :show="show8[0]" @open="sleectByZcId()">
              <van-picker
                title="资产名称"
                :columns="dataList"
                @confirm="onConfirm8"
                @cancel="onCancel8"
                @change="onChange8"
              />
            </van-popup>
          </template>
        </van-field>

        <van-button
          style="margin-top: 30px; background-color: #4b75e5"
          type="primary"
          block
          @click="qr()"
          >新增</van-button
        >
      </van-popup>
    </div>
  </van-list>
</template>

<style lang="stylus" scoped>
.page-main

  .working-list
    .item1
      padding-top 0px
      padding-bottom 0px
    .title1
      color #003586
      font-weight bolder
      font-size 13px
    .titles
      color #161718
      font-weight bolder
      font-size 13px
    .titless
      color #161718
      font-weight bolder
      font-size 17px
    .title2
      color #808080
      font-size 13px
    padding 4px
    margin-bottom 48px
    .van-tag
      margin-left 5px
      font-size 12px
      padding 5px
    .btn1
      background-color #038008
      border-radius 5px
      margin-left 5px
    .btn0
      background-color #ff8d1a
      border-radius 5px
      margin-left 5px
    .class1
      background-color #99bcf1
      border-radius 5px
    .class2
      background-color #f19999
      border-radius 5px
    .class3
      background-color #99a6f1
      border-radius 5px
    .card-item
      margin 8px
      background-color white

      .item-value
        display flex
        justify-content space-between
        overflow hidden
        text-overflow ellipsis
        word-break keep-all
        white-space nowrap
        background-color transparent
        .group1
          display flex
          flex-direction row
          justify-content space-between

  .bottom-buttons
    position fixed
    bottom 12px
    left auto
    width 100%
    max-width var(--max-width)
</style>
